package com.elric.mall.context;

import cn.hutool.core.util.StrUtil;
import com.elric.mall.dto.SysCodeGenerateConfig;
import com.elric.mall.dto.XnCodeGenParam;
import org.apache.velocity.VelocityContext;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 设置上下文缓存
 */
public class XnVelocityContext {

    /**
     * 创建上下文用到的参数
     */
    public VelocityContext createVelContext (XnCodeGenParam xnCodeGenParam) {
        VelocityContext velocityContext = new VelocityContext();

        // 功能名
        velocityContext.put("functionName",xnCodeGenParam.getFunctionName());

        // 业务名
        velocityContext.put("busName",xnCodeGenParam.getBusName());

        // 作者姓名
        velocityContext.put("authorName", xnCodeGenParam.getAuthorName());

        // 数据库表名
        velocityContext.put("tableName", xnCodeGenParam.getTableName());
        if (xnCodeGenParam.getConfigList() != null) {
            List<SysCodeGenerateConfig> formatedList = xnCodeGenParam.getConfigList().stream().map(c -> {
                c.setColumnKeyName(StrUtil.toCamelCase(c.getColumnName()));
                String type = c.getJavaType().toUpperCase();
                if (StrUtil.equals(c.getJavaType(), "datetime")) {
                    type = "TIMESTAMP";
                }
                c.setJavaType(type);
                return c;
            }).collect(Collectors.toList());
            // 数据库字段
            velocityContext.put("tableField", formatedList);
        }

        // 前端查询所有
        List<SysCodeGenerateConfig> codeGenerateConfigList = new ArrayList<>();
        xnCodeGenParam.getConfigList().forEach(item -> {
            if (item.getQueryWhether().equals("Y")) {
                codeGenerateConfigList.add(item);
            }
        });
        velocityContext.put("queryWhetherList", codeGenerateConfigList);

        // sql中id的创建
        List<Long> idList = new ArrayList<>();
        for (int a = 0; a <= 7; a++) {
            idList.add(Math.abs(UUID.randomUUID().getLeastSignificantBits()));
        }
        velocityContext.put("sqlMenuId", idList);

        return velocityContext;
    }
}
